package com.zzty.zzlp.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebFilter(filterName = "SessionFilter",urlPatterns="/*")
public class SessionFilter implements Filter {

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest)req;
		HttpServletResponse response=(HttpServletResponse)resp;
		
		String uri = request.getRequestURI();
		// filterChain.doFilter(request, response);
		System.out.println(uri);
		if (uri.contains("resetPassword.html") || uri.contains("login") || uri.contains("abate.html") || uri.contains("register.html")
		        || uri.contains("mailPwdReset.html") || uri.contains("agreement.html") || uri.contains("success.html") || uri.contains("/Register") || uri.contains("/ChangePassword")
				|| uri.contains("/login") || uri.contains("/css") || uri.contains("/img") ||uri.contains("/js")) {
			chain.doFilter(request, response);
		} else {
			Object obj = request.getSession().getAttribute("User");
			if (null == obj) {
				boolean isAjaxRequest = isAjaxRequest(request);
				if (isAjaxRequest) {
					response.setCharacterEncoding("UTF-8");
					response.sendError(401, "您已经太长时间没有操作,请刷新页面");
					return;
				}
				response.sendRedirect(request.getContextPath() +"/login");
				return;
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

	public void destroy() {

	}
	
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "AJAX".equals(header))
			return true;
		else
			return false;
	}

}
